package com.swordliu.facebook.config.springmvc;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * springMVCAdapter
 * Created by SwordLiu on 2017-07-14.
 */
@Configuration
public class SpringMvc extends WebMvcConfigurerAdapter {

    /**
     * 配置了shiro后，会优先触发shiro的验证不通过，跳转登录页面，
     * 已经登录的情况下，也就是只有通过了shiro验证，才会执行该方法来跳转
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("forward:login.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);

        super.addViewControllers(registry);
    }

    /**
     * 错误页面定义，错误页面一般放在static目录下，以静态资源方式调用
     * @return
     */
    @Bean
    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {

        //这是jdk1.8新功能，lambda语法，匿名实现接口函数， container为方法参数，当有两个以上参数时，用括号，中间逗号分隔
        EmbeddedServletContainerCustomizer customizer = container -> {
            //the path must start with "/".
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/extra_404.html");
            ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/extra_500.html");
            ErrorPage errorPage405 = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error/extra_405.html");

            container.addErrorPages(errorPage404, errorPage405, errorPage500);
        };

        return customizer;
    }

}
